local skel = fk.CreateSkill {
  name = "rmt__huizhuang",
}


Fk:loadTranslationTable{
  ["rmt__huizhuang"] = "麾幢",
  [":rmt__huizhuang"] = "出牌阶段，若你有手牌，你可以展示牌堆顶的一张牌，与一名其他角色各弃置一张牌。最靠近展示牌点数的角色选择一项，另一名角色选择另一项："
  .."1.使用展示牌；2.将一张弃置牌置于牌堆顶；3.令你摸两张牌并结束当前回合。",

  ["rmt__huizhuang-prompt"] = "是否想发动“麾幢”，展示牌堆顶的一张牌，与一名其他角色各弃置一张牌？",
  ["rmt__huizhuang-discard"] = "请弃置一张牌，接近 %arg 点的角色先选择一项执行",
  ["rmt__huizhuang-use"] = "使用 %arg",
  ["rmt__huizhuang-putToTop"] = "将一张弃置牌置于牌堆顶",
  ["rmt__huizhuang-drawAndBreak"] = "令 %src 摸两张牌并结束当前回合",

  ["rmt__huizhuang-choice"] = "麾幢：请选择一项",
  ["rmt__huizhuang-put"] = "麾幢：将一张弃置牌置于牌堆顶",
}

skel:addEffect("active", {
  anim_type = "drawcard",
  prompt = "rmt__huizhuang-prompt",
  can_use = function (self, player)
    return not player:isKongcheng()
  end,
  card_num = 0,
  target_num = 1,
  target_filter = function (self, player, to_select, selected)
    return #selected == 0 and to_select ~= player and not to_select:isNude()
  end,
  on_use = function (self, room, effect)
    local player = effect.from
    local target = effect.tos[1]
    local top_card = room:getNCards(1)
    room:moveCardTo(top_card, Card.Processing, nil, fk.ReasonJustMove, skel.name)

    local top_num = Fk:getCardById(top_card[1]).number

    local cardsMap = room:askToJointCards(player, {
      skill_name = skel.name, min_num = 1, max_num = 1, players = {player, target}, cancelable = false,
      will_throw = true, pattern = ".", prompt = "rmt__huizhuang-discard:::" .. top_num
    })

    room:moveCards({
      ids = cardsMap[player],
      from = player,
      toArea = Card.DiscardPile,
      moveReason = fk.ReasonDiscard,
      proposer = player,
    }, {
      ids = cardsMap[target],
      from = target,
      toArea = Card.DiscardPile,
      moveReason = fk.ReasonDiscard,
      proposer = target,
    })

    local all_discards = {}
    local player_num, target_num
    if #cardsMap[player] > 0 then -- 小心禁止弃置
      player_num = Fk:getCardById(cardsMap[player][1]).number
      table.insert(all_discards, cardsMap[player][1])
    end
    if #cardsMap[target] > 0 then
      target_num = Fk:getCardById(cardsMap[target][1]).number
      table.insert(all_discards, cardsMap[target][1])
    end

    local winner
    if player_num and target_num then -- 两者相同则没有赢家，不执行
      if math.abs(player_num - top_num) < math.abs(target_num - top_num) then
        winner = player
      elseif math.abs(player_num - top_num) > math.abs(target_num - top_num) then
        winner = target
      end
    elseif player_num or target_num then -- 如果只有1名角色弃置牌，则他为赢家
      winner = player_num and player or target
    end

    if not winner then
      if room:getCardArea(top_card[1]) == Card.Processing then
        room:moveCardTo(top_card, Card.DrawPile, nil, fk.ReasonPut, skel.name, nil, true, player)
      end
      if player:usedSkillTimes(skel.name, Player.HistoryPhase) > 20 then -- 防止死循环哈
        room:invalidateSkill(player, skel.name, "-phase")
      end
      return
    end

    local all_choices = {
      skel.name.."-use:::"..Fk:getCardById(top_card[1]):toLogString(),
      skel.name.."-putToTop",
      skel.name.."-drawAndBreak:"..player.id,
    }

    ---@param chooser ServerPlayer
    ---@param remove_choice string?
    ---@return string
    local doChoose = function (chooser, remove_choice)
      local choices = table.simpleClone(all_choices)
      if #Fk:getCardById(top_card[1]):getDefaultTarget(chooser, {bypass_times = true}) == 0 then
        table.remove(choices, 1)
      end
      if not table.find(all_discards, function(id) return room:getCardArea(id) == Card.DiscardPile end) then
        table.removeOne(choices, all_choices[2])
      end
      if remove_choice then
        table.removeOne(choices, remove_choice)
      end
      if #choices == 0 then return "" end
      return room:askToChoice(chooser, { choices = choices, skill_name = skel.name, prompt = skel.name.."-choice", all_choices = all_choices})
    end

    ---@param proposer ServerPlayer
    ---@param choice string
    local doEffect = function(proposer, choice)
      if choice == all_choices[3] then
        if not player.dead then
          player:drawCards(2)
        end
        room:endTurn()
      elseif choice == all_choices[2] then
        local to_put = table.filter(all_discards, function (id)
          return room:getCardArea(id) == Card.DiscardPile
        end)
        if #to_put > 0 then
          local put = room:askToChooseCard(proposer, {
            target = player, skill_name = skel.name, prompt = skel.name.."-put",
            flag = { card_data = { { "Top", to_put } } }
          })
          room:moveCardTo(put, Card.DrawPile, nil, fk.ReasonPut, skel.name, nil, true, proposer)
        end
      elseif choice == all_choices[1] then
        room:askToUseRealCard(proposer, {
          skill_name = skel.name, cancelable = false, pattern = top_card, expand_pile = top_card,
          prompt = skel.name.."-use:::"..Fk:getCardById(top_card[1]):toLogString(),
          extra_data = {bypass_times = true, expand_pile = top_card},
        })
      end
    end

    local choiceA, choiceB
    if winner:isAlive() then
      choiceA = doChoose(winner)
      doEffect(winner, choiceA)
    end
    local other = winner == player and target or player
    if other:isAlive() then
      choiceB = doChoose(other, choiceA)
      doEffect(other, choiceB)
    end

    if room:getCardArea(top_card[1]) == Card.Processing then
      room:moveCardTo(top_card, Card.DrawPile, nil, fk.ReasonPut, skel.name, nil, true, player)
    end
  end
})


return skel
